<?php
namespace App\Http\Controllers;

use App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Service\TaobaoService;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Validator;

class OrderController extends BaseController
{
    
    public $repository;
    public function __construct(TaobaoService $repository)
    {
        parent::__construct();
        $this->repository = $repository;
    }
    public function getList()
    {

        // 配置参数
        $appKey = "114972200337";
        $appSecret = "b35eea36f7b2359c0b4f3ee88b75d985";
        $session = "USER_SESSION_TOKEN"; // 用户授权Token
        $startTime = "2025-01-01 00:00:00";
        $endTime = "2025-01-01 23:59:59";
        $queryType = 1; // 按淘客订单创建时间查询

        // 公共参数
        $params = [
            'method' => 'taobao.tbk.sc.order.details.get',
            'app_key' => $appKey,
            'session' => $session,
            'timestamp' => date('Y-m-d H:i:s'),
            'format' => 'json',
            'v' => '2.0',
            'sign_method' => 'md5',
            'start_time' => $startTime,
            'end_time' => $endTime,
            'query_type' => $queryType,
            'page_no' => 1,       // 第一页
            'page_size' => 20,    // 每页20条
        ];

        // 生成签名
        ksort($params);
        $signString = $appSecret;
        foreach ($params as $k => $v) {
            $signString .= "$k$v";
        }
        $signString .= $appSecret;
        $params['sign'] = strtoupper(md5($signString));

        // 发送请求
        $url = "https://eco.taobao.com/router/rest?" . http_build_query($params);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $response = curl_exec($ch);
        curl_close($ch);

        // 处理结果
        $result = json_decode($response, true);
        if (isset($result['tbk_sc_order_details_get_response']['data'])) {
            $orders = $result['tbk_sc_order_details_get_response']['data']['results'];
            foreach ($orders as $order) {
                // 处理订单数据
                echo "订单ID: " . $order['tk_order_id'] . "\n";
            }
        } else {
            echo "请求失败: " . print_r($result, true);
        }

    }
    //获取全部订单
    public function getListttt(Request $request)
    {
        $startTime = "2025-01-01 00:00:00";
        $endTime = "2025-01-01 23:59:59";

        // 获取用户授权session（实际从数据库获取）
        $session = ''; 
        #dd($session);
        $response = $this->repository->getScOrders(
            startTime:$startTime,
            endTime: $endTime,
            queryType: 1, // 按创建时间查询
            session: $session,
            tkStatus: 3   // 只查结算成功订单
        );
        
        // 处理分页数据
        $orders = data_get($response, 'tbk_sc_order_details_get_response.data.results.n_tbk_order', []);
        $hasNext = data_get($response, 'tbk_sc_order_details_get_response.data.has_next', false);
        dd($orders);

        
    }

    
}
